import express from "express"
import { Request, Response } from "express";
import { AppDataSource } from "../config/database";

const router = express.Router();
import { User } from "../entities/User";
import { failure, success } from "../utils/responses";
import { AuthRequest } from "../middlewares/user-auth";
import { BadRequest } from "http-errors";
import { getFileDownloadUrl } from "../utils/qiniuyun";


interface UserUpdateBody {
  username: string
}

/**
 * 获取当前登录用户信息
 */
router.get("/", async function (req: Request, res: Response) {
  try {
    const id = (req as AuthRequest).id
    const userRepository = AppDataSource.getRepository(User)
    const currentUser = await userRepository.findOneBy({ id })
    // 更新用户头像地址
    const avatar = currentUser.avatar // 数据库取出头像地址
    const url = avatar.split('?')[0]
    const filename = 'upload/' + url.slice(url.lastIndexOf('/') + 1) // 拿到文件名
    currentUser.avatar = getFileDownloadUrl(filename) // 获取最新的地址
    await userRepository.save(currentUser) // 更新头像
    const data = filterUser(currentUser) as User // 过滤当前用户对象的信息
    success(res, '获取用户信息成功', data)
  } catch (error) {
    failure(res, error)
  }
})

/**
 * 更新当前用户的用户名
 */
router.put("/updateUsername", async function (req: Request, res: Response) {
  try {
    const id = (req as AuthRequest).id
    const newUsername = (req.body as UserUpdateBody).username // 新用户名
    // 用户名非空校验
    if (!newUsername) throw new BadRequest("用户名不能为空")
    const userRepository = AppDataSource.getRepository(User)
    const user = await userRepository.findOneBy({ id })
    user.username = newUsername // 更新用户名
    await userRepository.save(user)

    const data = filterUser(user) as User // 过滤当前用户对象的信息
    success(res, '更新用户名成功', data)
  } catch (error) {
    failure(res, error)
  }
})

/**
 * 更新当前用户的头像
 */

router.put("/updateAvatar", async function (req: Request, res: Response) {
  try {
    const avatar = req.query.avatar as string
    if (!avatar) throw new BadRequest("头像地址不能为空")

    // 更新用户头像
    const id = (req as AuthRequest).id
    const userRepository = AppDataSource.getRepository(User)
    const user = await userRepository.findOneBy({ id })
    user.avatar = avatar // 更新头像地址
    await userRepository.save(user)

    success(res, '更新头像成功')
  } catch (error) {
    failure(res, error)
  }
})

/**
 * 过滤返回的用户信息
 * @param user
 */
export function filterUser(user: User) {
  return {
    id: user.id,
    phoneNumber: user.phoneNumber,
    avatar: user.avatar,
    username: user.username,
    role: user.role,
    score: user.score,
  }
}

export default router;